package common

import "fmt"

// DefaultProtocolFactory 默认协议工厂实现
type DefaultProtocolFactory struct {
	protocolCreators map[ProtocolType]func() Protocol
	builderCreators  map[ProtocolType]func() ProtocolBuilder
}

// NewDefaultProtocolFactory 创建默认协议工厂
func NewDefaultProtocolFactory() *DefaultProtocolFactory {
	return &DefaultProtocolFactory{
		protocolCreators: make(map[ProtocolType]func() Protocol),
		builderCreators:  make(map[ProtocolType]func() ProtocolBuilder),
	}
}

// RegisterProtocol 注册协议创建函数
func (f *DefaultProtocolFactory) RegisterProtocol(protocolType ProtocolType, creator func() Protocol) {
	f.protocolCreators[protocolType] = creator
}

// RegisterBuilder 注册构建器创建函数
func (f *DefaultProtocolFactory) RegisterBuilder(protocolType ProtocolType, creator func() ProtocolBuilder) {
	f.builderCreators[protocolType] = creator
}

// CreateProtocol 创建协议实例
func (f *DefaultProtocolFactory) CreateProtocol(protocolType ProtocolType) (Protocol, error) {
	creator, exists := f.protocolCreators[protocolType]
	if !exists {
		return nil, fmt.Errorf("不支持的协议类型: %s", protocolType.String())
	}
	return creator(), nil
}

// CreateBuilder 创建协议构建器
func (f *DefaultProtocolFactory) CreateBuilder(protocolType ProtocolType) (ProtocolBuilder, error) {
	creator, exists := f.builderCreators[protocolType]
	if !exists {
		return nil, fmt.Errorf("不支持的构建器类型: %s", protocolType.String())
	}
	return creator(), nil
}

// GetSupportedTypes 获取支持的协议类型
func (f *DefaultProtocolFactory) GetSupportedTypes() []ProtocolType {
	types := make([]ProtocolType, 0, len(f.protocolCreators))
	for protocolType := range f.protocolCreators {
		types = append(types, protocolType)
	}
	return types
}

// ParseProtocol 解析协议数据
func (f *DefaultProtocolFactory) ParseProtocol(data []byte) (Protocol, error) {
	if len(data) < 7 {
		return nil, fmt.Errorf("数据包太短")
	}
	
	// 检查起始位
	if data[0] != StartByte1 || data[1] != StartByte2 || data[2] != StartByte3 || data[3] != StartByte4 {
		return nil, fmt.Errorf("无效的起始位")
	}
	
	// 获取协议类型
	protocolType := ProtocolType(data[6])
	
	// 创建对应的协议实例
	protocol, err := f.CreateProtocol(protocolType)
	if err != nil {
		return nil, fmt.Errorf("创建协议失败: %w", err)
	}
	
	// 反序列化
	if err := protocol.Unmarshal(data); err != nil {
		return nil, fmt.Errorf("反序列化失败: %w", err)
	}
	
	return protocol, nil
}

// 全局工厂实例
var GlobalFactory = NewDefaultProtocolFactory()